package com.study.service.impl;

import com.study.bean.Seckill;
import com.study.service.SeckillService;
import com.study.utils.DatePattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    StringRedisTemplate redisTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:session:";

    @Override
    public void uploadSeckillSkuLatest3Days() {
        List<Seckill> queryForList = jdbcTemplate.query("select * from sms_seckill_session",
                new BeanPropertyRowMapper(Seckill.class));
        //计算最近三天的时间
        // 查询数据保存到redis中
        queryForList.forEach((item) -> {
            long startTime = item.getStartTime().getTime();
            long endTime = item.getEndTime().getTime();
            //redis中key
            String key = String.format("%s$s_%s", startTime, endTime);
            redisTemplate.opsForList().leftPushAll(key, Arrays.asList("a", "b", "c"));
        });
    }

    /**
     * 计算最近三天的时间
     *
     * @return
     */
    private String startTime() {
        LocalDateTime of = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        return of.format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN));
    }

    /**
     * 计算最近三天的时间
     *
     * @return
     */
    private String emdTime() {
        return LocalDateTime.of(LocalDate.now().plusDays(2), LocalTime.MAX)
                .format((DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
    }
}
